package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("拦截器："+requestURL);
        String token = request.getHeader("ACCESS_TOKEN");

        if(!StringUtils.hasText(token)){
            // 用户未登录
            throw new RuntimeException("用户没有登录");
        }else {
            // 解析token
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId",Long.class);
            String username = claims.get("username", String.class);
            // 放入本地线程
            LoginUser loginUser = new LoginUser();
            loginUser.setUserId(userId);
            loginUser.setUsername(username);
            LoginUserContext.setLoginUser(loginUser);
        }

        return true;
    }

    /**
     * 防止本地线程占用空间导致内存泄露
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LoginUserContext.remove();
    }

}
